package cn.cxq.learning.tree;

import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        if (pre == null || pre.length == 0) {
            return null;
        }
        
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < vin.length; i++) {
            map.put(vin[i], i);
        }
        
        return reConstructBinaryTree(pre, 0, pre.length - 1, vin, 0, vin.length - 1, map);
    }
    
    private TreeNode reConstructBinaryTree (int[] pre, int pl, int pr, int[] in, int il, int ir, Map<Integer, Integer> inIndex ) {
        if (pl > pr) {
            return null;
        }
        
        TreeNode root = new TreeNode(pre[pl]);
        
        int index = inIndex.get(pre[pl]);
        
        int sizeOfLeftTree = index - il;
        
        root.left = reConstructBinaryTree (pre, pl + 1, pl + sizeOfLeftTree, in, il, index - 1, inIndex);
        root.right = reConstructBinaryTree (pre,  pl + sizeOfLeftTree + 1, pr, in, index + 1, ir, inIndex);
        
        return root;
    }
}